package org.volicy.mysql.schema.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.FileUrlResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.volicy.mysql.schema.interceptor.MysqlSchemaInterceptor;

import javax.sql.DataSource;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: volicy.xu
 * @Date: 2021/9/15
 */
@Configuration
//@ConditionalOnClass({DefaultSqlSessionFactory.class, MybatisAutoConfiguration.class})
@ConditionalOnProperty(prefix = "spring.enable.single.data",name = "source" ,havingValue = "on")
@EnableConfigurationProperties(MysqlSchemaProperties.class)
@AutoConfigureAfter(value = DataSourceAutoConfiguration.class)
public class MysqlSchemaAutoConfiguration {
    private Logger logger = LoggerFactory.getLogger(MysqlSchemaAutoConfiguration.class);

    private Pattern pattern = Pattern.compile("\\w+\\.(\\w+)\\.url");
    private Pattern urlPattern = Pattern.compile("^//(\\d+\\.){3}(\\d+):(\\d+)/(\\w+)");
    @Autowired
    private MysqlSchemaProperties mysqlSchemaProperties;

    @Bean
    public MysqlSchemaInterceptor mysqlSchemaInterceptor() {
        logger.info("MysqlSchemaAutoConfiguration -- init ....");
        return new MysqlSchemaInterceptor();
    }

    @Bean(name = "drpTransactionManager")//为了支持多数据源，项目中的事务，临时添加上了这个
    @Primary
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

//    @Autowired //目前先不做处理，datasource里面mysql配置是在另外一台服务器上
//    public void handleDataSourceFile() {
//        try {
//            PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
//            propertiesFactoryBean.setLocation(new FileUrlResource("/hm/config/datasources.properties"));
//            propertiesFactoryBean.afterPropertiesSet();
//            Properties properties = propertiesFactoryBean.getObject();
//            if (properties != null) {
//                properties.stringPropertyNames().stream().forEach(name -> {
//                    Matcher matcher = pattern.matcher(name);
//                    if (matcher.matches()) {
//                        Matcher matcher0 = urlPattern.matcher(properties.getProperty(name));
//                        mysqlSchemaProperties.getDataSourceMapping().put(matcher.group(1), matcher0.matches() ? matcher0.group(4) : null);
//                    }
//                });
//            }
//        } catch (Exception ex) {
//            logger.warn("properties file does not exist... ");
//        }
//    }
}
